var table;
$(function () {
    /**
     * 初始化红包列表
     */
    var initCrowdFundTable = function () {
        chinese.sInfo = "共 _TOTAL_ 条";
        chinese.sInfoEmpty = "";
        table = $('#crowdFundList').DataTable({
            "sort": false,
            "search": false,
            "ajax": {
                "url": "pointsystem/getCrowdFundList",
                "type": "POST"
            },
            "aoColumnDefs": [{
                    "targets": 0,
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                },{
                    "targets": 1,
                    "mRender": function (data, type, row) {
                        return row.period + "期";
                    }
                }, {
                    "targets": 2,
                    "mRender": function (data, type, row) {
                        return row.commodityName;
                    }
                }, {
                    "targets": 3,
                    "mRender": function (data, type, row) {
                        return row.sumPoint;
                    }
                }, {
                    "targets": 4,
                    "mRender": function (data, type, row) {
                        return row.loginName === null ? "---" : row.loginName;
                    }
                },{
                    "targets": 5,
                    "mRender": function (data, type, row) {
                        return row.remark;
                    }
                }, {
                    "targets": 6,
                    "mRender": function (data, type, row) {
                        return row.default ? "是" : "否";
                    }
                }, {
                    "targets": 7,
                    "mRender": function (data, type, row) {
                        var operations = $("#operationHTML").html().replace(/#id/g, row.id);
                        return operations;
                    }
                }],
            "oLanguage": chinese,
            "iDisplayLength": 10,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lip>',
            "fnDrawCallback": function () {
                $("#crowdFundAdd").click(function () {
                    show("");
                });
            }
        });

        
        
    };

    initCrowdFundTable();
    initCommodity();
    var step = 1;
    /**
     * 详情展开/关闭
     */
    $('#crowdFundList tbody').on('click', 'td.details-control', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var tr = $(this).closest('tr');
        var row = table.row(tr);
        if (row.child.isShown()) {
            // 关闭详情
            $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
            row.child.hide();
            tr.removeClass('shown');
        } else {
            // 展开详情
            $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
            var crowdId = row.data().id, detail = '<p class="text-center mt20 mb20">尚无满足条件的竞拍品</p>';
            var content = {}, sub = {}, members = [];
            content.placements = members;
            $.get("pointsystem/getSnapupRecord", {id: crowdId}, function (res) {
                if (res.recordsTotal > 0) {
                    var section = -1;
                    for (var i = res.recordsTotal-1; i >= 0 ; i--) {
                        var sub = res.data[i];
                        sub.num = sub.points/step;
                        sub.sno = (section + 1) + "-" + (section + sub.points/step);
                        section += sub.points/step;
                        sub.isAllot = res.draw === 0;
                        members.push(sub);
                    }
                    detail = sys.render("#crowdTemplate", content);
                }
                row.child(detail).show();
                tr.addClass('shown');
            });
        }
    });
    $('#crowdFundList tbody').on('click', '.edit', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var tid = $(this).data("tid"), uid = $(this).data("uid"),pointId = $(this).data("pointid"), btn = $(this);
        sys.confirm("确定设为中奖者？", function () {
            sys.processModal();
            $.post("pointsystem/setCrowdFundWinner",{id:tid, userId: uid, pointId: pointId}, function (res) {
                if (res.success) {
                    alert("操作成功");
                    location.reload();
                } else {
                    alert("操作失败");
                    sys.closeModal();
                }
            }).fail(function () {
                alert("网络通信错误");
                sys.closeModal();
            });
        });
    });
});


function setDefault(id) {
    $.get("pointsystem/setDefaultCrowdFund/" + id, function (res) {
        if (res.success) {
            alert("设置成功");
            location.reload();
        } else {
            alert("设置默认夺宝失败");
        }
    });
}

function show(id){
    $("#crowdFundId").val("");
    $("#confirm").unbind();
    if(id === ""){
        $("#period").val("");
        $("#commotity option").eq(0).attr("selected", true);
        $("#sumPoint").val(0);
        $("#remark").val("");
        $("#isDefault").removeAttr("checked");
        $("#confirm").click(function(){addCrowdFund();});
    }else{
        $.get("pointsystem/getCrowdFund/" + id, function (res) {
            if (res.success) {
                var data = res.model;
                $("#period").val(data.period);
                $("#commotity").val(data.commodityId);
                $("#sumPoint").val(data.sumPoint);
                $("#remark").val(data.remark);
                if(data.default){
                    $("#isDefault").attr("checked", true);
                }else{
                    $("#isDefault").removeAttr("checked");               
                }
            } else {
                alert("获取活动数据失败");
            }
        });
        $("#confirm").click(function(){updateCrowdFund();});
        $("#crowdFundId").val(id);
    }
    $('#myModal').modal('show');
}

var initCommodity = function(){
    $.get("pointsystem/getCommodityList", function (res) {
        if (res.data) {
            var data = res.data;
            var content = "";
            for(var i = 0; i < data.length; i++){
                content += "<option value='"+data[i].id+"'>"+data[i].cname+"</option>";
            }
            $("#commotity").html(content);
        } else {
            alert("获取商品数据失败");
        }
    });
};

var addCrowdFund = function(){
    var period = $("#period").val();
    var commodityId = $("#commotity").val();
    var sumPoint = $("#sumPoint").val();
    var remark = $("#remark").val();
    var isDefault = $("#isDefault").is(":checked");
    $.post("pointsystem/addCrowdFund",{commodityId: commodityId, sumPoint: sumPoint, period: period, remark: remark, isDefault: isDefault} ,function (res) {
        if (res.success) {
            alert("添加成功");
            location.reload();
        } else {
            alert("添加失败");
        }
    });
    
};

var updateCrowdFund = function(){
    var id = $("#crowdFundId").val();
    var period = $("#period").val();
    var commodityId = $("#commotity").val();
    var sumPoint = $("#sumPoint").val();
    var remark = $("#remark").val();
    var isDefault = $("#isDefault").is(":checked");
    $.post("pointsystem/updateCrowdFund",{id: id, commodityId: commodityId, sumPoint: sumPoint, period: period, remark: remark, isDefault: isDefault} ,function (res) {
        if (res.success) {
            alert("修改成功");
            location.reload();
        } else {
            alert("修改失败");
        }
    });
};